package org.snia.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.snia.cdmi.model.DataObjectVersion;
import org.snia.cdmi.model.MetaContainer;
import org.snia.cdmi.model.MetaDataObject;
import org.snia.cdmi.model.MetaSliceData;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class SerializeUtil {
	private static Log log = LogFactory.getLog(SerializeUtil.class);
	
	public static void main(String[] args) {
	}

	/**
	 * 将对象序列化为一个文件
	 * @param object 要序列化的对象实体
	 * @param path 序列化后的文件路径
	 */
	public static void serializeToXml(Object object, String path) {
		XStream xs = new XStream();
		xs.alias("Container", MetaContainer.class);
		xs.alias("DataObject", MetaDataObject.class); 
		xs.alias("DataObjectVersion", DataObjectVersion.class);
		xs.alias("DataSlice", MetaSliceData.class);
		
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(path);
			xs.toXML(object, fos);
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
			log.error(ex.getMessage());
		} finally {
			try {
				if(fos != null){
					fos.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
				//忽略
			}
		}
		System.out.println(xs.toXML(object));
	}

	/**
	 * 读取文件，将文件内容反序列化为对象
	 * @param path 要读取的文件全路径
	 * @return
	 */
	public static Object deSerializeFromXml(String path) {
		XStream xs = new XStream(new DomDriver());
		xs.alias("Container", MetaContainer.class);
		xs.alias("DataObject", MetaDataObject.class); 
		xs.alias("DataObjectVersion", DataObjectVersion.class);
		xs.alias("DataSlice", MetaSliceData.class);
		
		FileInputStream fis = null;
		Object object = null;
		try {
			fis = new FileInputStream(path);
			object = xs.fromXML(fis);
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
			log.error(ex.getMessage());
		} finally {
			try {
				if(fis != null){
					fis.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
				//忽略
			}
		}
		return object;
	}
}
